//
// Copyright (C) 2011 - 2013  Steve Channell steve.channell@cepheis.com
//
// This file is part of Cephei.QL, an open-source library wrapper 
// arround QuantLib http://quantlib.org/
//
// Cephei.QL is open source software: you can redistribute it and/or modify it
// under the terms of the license.  You should have received a
// copy of the license along with this program; if not, please email
// <support@cepheis.com>. The license is also available online at
// <http://cepheis.com/license.htm>.
//
// This program is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
// FOR A PARTICULAR PURPOSE.  See the license for more details.
//
// Version 2.2 with QuantLib 1.2.1
//#include "stdafx.h"
#include "LiborForwardModel.h"
using namespace Cephei::QL::Legacy::Libormarketmodels;
#include <gen/QL/Math/Array.h>
#include <gen/QL/Termstructures/Volatility/Swaption/SwaptionVolatilityMatrix.h>
#include <gen/QL/Legacy/Libormarketmodels/LiborForwardModelProcess.h>
#include <gen/QL/Legacy/Libormarketmodels/LmVolatilityModel.h>
#include <gen/QL/Legacy/Libormarketmodels/LmCorrelationModel.h>
#include <gen/QL/Models/CalibrationHelper.h>
#include <gen/QL/Math/Optimization/OptimizationMethod.h>
#include <gen/QL/Math/Optimization/EndCriteria.h>
#include <gen/QL/Math/Optimization/Constraint.h>
#include <gen/QL/Models/CalibratedModel.h>
#include <gen/QL/Models/AffineModel.h>
using namespace Cephei::QL::Math;
using namespace Cephei::QL::Termstructures::Volatility::Swaption;
using namespace Cephei::QL::Models;
using namespace Cephei::QL::Math::Optimization;
#define HANDLE
#undef ABSTRACT
#undef STRUCT
Cephei::QL::Legacy::Libormarketmodels::CLiborForwardModel::CLiborForwardModel (Cephei::QL::Legacy::Libormarketmodels::ILiborForwardModelProcess^ process, Cephei::QL::Legacy::Libormarketmodels::ILmVolatilityModel^ volaModel, Cephei::QL::Legacy::Libormarketmodels::ILmCorrelationModel^ corrModel) : CCalibratedModel(CLiborForwardModel::typeid)
{
    CLiborForwardModelProcess^ _Cprocess;
    CLmVolatilityModel^ _CvolaModel;
    CLmCorrelationModel^ _CcorrModel;
    try
    {
#ifdef HANDLE
        _phLiborForwardModel = NULL;
#endif
        _Cprocess = safe_cast<CLiborForwardModelProcess^> (process);
        _Cprocess->Lock();
        boost::shared_ptr<QuantLib::LiborForwardModelProcess>& _process = static_cast<boost::shared_ptr<QuantLib::LiborForwardModelProcess>&> (_Cprocess->GetShared ()); 
        _CvolaModel = safe_cast<CLmVolatilityModel^> (volaModel);
        _CvolaModel->Lock();
        boost::shared_ptr<QuantLib::LmVolatilityModel>& _volaModel = static_cast<boost::shared_ptr<QuantLib::LmVolatilityModel>&> (_CvolaModel->GetShared ()); 
        _CcorrModel = safe_cast<CLmCorrelationModel^> (corrModel);
        _CcorrModel->Lock();
        boost::shared_ptr<QuantLib::LmCorrelationModel>& _corrModel = static_cast<boost::shared_ptr<QuantLib::LmCorrelationModel>&> (_CcorrModel->GetShared ()); 
        _ppLiborForwardModel = new boost::shared_ptr<QuantLib::LiborForwardModel> (new QuantLib::LiborForwardModel ( _process,  _volaModel,  _corrModel ));
        SetCalibratedModel (boost::dynamic_pointer_cast<QuantLib::CalibratedModel> (*_ppLiborForwardModel));
	}
    catch (QuantLib::Error& _error)
    {
        if (_error.what())
		    throw REFNEW NativeExcpetion (REFNEW PLATFORM::String(_error.what()));
        else
		    throw REFNEW NativeExcpetion (REFNEW PLATFORM::String("Unknown quantlib error"));
        
    }
	catch (std::exception& _error)
	{
        if (_error.what())
		    throw REFNEW NativeExcpetion (REFNEW PLATFORM::String(_error.what()));
        else
		    throw REFNEW NativeExcpetion (REFNEW PLATFORM::String("Unknown std::exception"));
	}
    finally
    {
        if (_Cprocess != nullptr) _Cprocess->Unlock();
        if (_CvolaModel != nullptr) _CvolaModel->Unlock();
        if (_CcorrModel != nullptr) _CcorrModel->Unlock();
    }
}
Cephei::QL::Legacy::Libormarketmodels::CLiborForwardModel::CLiborForwardModel (boost::shared_ptr<QuantLib::LiborForwardModel>& childNative, Object^ owner) : CCalibratedModel(CLiborForwardModel::typeid)
{
#ifdef HANDLE
	_phLiborForwardModel = NULL;
#endif
	_ppLiborForwardModel = &childNative;
    _ppCalibratedModel = new boost::shared_ptr<QuantLib::CalibratedModel> (boost::dynamic_pointer_cast<QuantLib::CalibratedModel> (*_ppLiborForwardModel));
}
Cephei::QL::Legacy::Libormarketmodels::CLiborForwardModel::CLiborForwardModel (QuantLib::LiborForwardModel& childNative, Object^ owner) : CCalibratedModel(CLiborForwardModel::typeid)
{
#ifdef HANDLE
	_phLiborForwardModel = NULL;
#endif
	_ppLiborForwardModel = new boost::shared_ptr<QuantLib::LiborForwardModel> (&childNative);
    _ppCalibratedModel = new boost::shared_ptr<QuantLib::CalibratedModel> (boost::dynamic_pointer_cast<QuantLib::CalibratedModel> (*_ppLiborForwardModel));
    _LiborForwardModelOwner = owner;
    _CalibratedModelOwner = owner;
}

Cephei::QL::Legacy::Libormarketmodels::CLiborForwardModel::CLiborForwardModel (CLiborForwardModel^ copy) : CCalibratedModel(CLiborForwardModel::typeid)
{
#ifdef HANDLE
	_phLiborForwardModel = NULL;
#endif
	if (copy->HasNative() != NULL)
    {
		_ppLiborForwardModel = new boost::shared_ptr<QuantLib::LiborForwardModel> (copy->GetShared());
        _ppCalibratedModel = new boost::shared_ptr<QuantLib::CalibratedModel> (boost::dynamic_pointer_cast<QuantLib::CalibratedModel> (*_ppLiborForwardModel));
    }
}
Cephei::QL::Legacy::Libormarketmodels::CLiborForwardModel::CLiborForwardModel (PLATFORM::Type^ t) : CCalibratedModel(CLiborForwardModel::typeid)
{
#ifdef HANDLE
	_phLiborForwardModel = NULL;
#endif
	if (!t->IsSubclassOf(CLiborForwardModel::typeid))
		throw REFNEW Exception ("Invalid base-case init");
}
#ifdef HANDLE
Cephei::QL::Legacy::Libormarketmodels::CLiborForwardModel::CLiborForwardModel (QuantLib::Handle<QuantLib::LiborForwardModel>& childNative, Object^ owner)  : CCalibratedModel(CLiborForwardModel::typeid)
{
	_phLiborForwardModel = &childNative;
	_ppLiborForwardModel = &static_cast<boost::shared_ptr<QuantLib::LiborForwardModel>>(childNative.currentLink());
    _ppCalibratedModel = new boost::shared_ptr<QuantLib::CalibratedModel> (boost::dynamic_pointer_cast<QuantLib::CalibratedModel> (*_ppLiborForwardModel));
    _LiborForwardModelOwner = owner;
}
Cephei::QL::Legacy::Libormarketmodels::CLiborForwardModel::CLiborForwardModel (QuantLib::Handle<QuantLib::LiborForwardModel> childNative)  : CCalibratedModel(CLiborForwardModel::typeid)
{
	_phLiborForwardModel = &childNative;
	_ppLiborForwardModel = &static_cast<boost::shared_ptr<QuantLib::LiborForwardModel>>(childNative.currentLink());
    _ppCalibratedModel = new boost::shared_ptr<QuantLib::CalibratedModel> (boost::dynamic_pointer_cast<QuantLib::CalibratedModel> (*_ppLiborForwardModel));
}
#endif
#ifdef STRUCT
Cephei::QL::Legacy::Libormarketmodels::CLiborForwardModel::CLiborForwardModel (QuantLib::LiborForwardModel childNative)  : CCalibratedModel(CLiborForwardModel::typeid)
{
#ifdef HANDLE
	_phLiborForwardModel = NULL;
#endif
	_ppLiborForwardModel = new boost::shared_ptr<QuantLib::LiborForwardModel> (new QuantLib::LiborForwardModel (childNative));
    _ppCalibratedModel = new boost::shared_ptr<QuantLib::CalibratedModel> (boost::dynamic_pointer_cast<QuantLib::CalibratedModel> (*_ppLiborForwardModel));
}
#endif

Cephei::QL::Legacy::Libormarketmodels::CLiborForwardModel::~CLiborForwardModel ()
{
    if (_ppLiborForwardModel != NULL)
    {
	    delete _ppLiborForwardModel;
        _ppLiborForwardModel = NULL;
    }
}
Cephei::QL::Legacy::Libormarketmodels::CLiborForwardModel::!CLiborForwardModel ()
{
    if (_ppLiborForwardModel != NULL)
    {
	    delete _ppLiborForwardModel;
    }
}
QuantLib::LiborForwardModel& Cephei::QL::Legacy::Libormarketmodels::CLiborForwardModel::GetReference ()
{
    if (_ppLiborForwardModel == NULL) throw REFNEW NativeNullException ();
	return **_ppLiborForwardModel;
}
boost::shared_ptr<QuantLib::LiborForwardModel>& Cephei::QL::Legacy::Libormarketmodels::CLiborForwardModel::GetShared ()
{
    if (_ppLiborForwardModel == NULL) throw REFNEW NativeNullException ();
	return *_ppLiborForwardModel;
}
QuantLib::LiborForwardModel* Cephei::QL::Legacy::Libormarketmodels::CLiborForwardModel::GetPointer ()
{
    if (_ppLiborForwardModel == NULL) throw REFNEW NativeNullException ();
	return &**_ppLiborForwardModel;
}
#ifdef HANDLE
QuantLib::Handle<QuantLib::LiborForwardModel>& Cephei::QL::Legacy::Libormarketmodels::CLiborForwardModel::GetHandle ()
{
	if (_phLiborForwardModel == NULL)
	{
		_phLiborForwardModel = new Handle<QuantLib::LiborForwardModel> (*_ppLiborForwardModel);
	}
	return *_phLiborForwardModel;
}
#endif
bool Cephei::QL::Legacy::Libormarketmodels::CLiborForwardModel::HasNative () 
{
	return (_ppLiborForwardModel != NULL);
}

Double Cephei::QL::Legacy::Libormarketmodels::CLiborForwardModel::Discount (Double t)
{
    try
    {
        QuantLib::Time _t = (QuantLib::Time)ValueHelper::Convert (t); //a
    	QuantLib::DiscountFactor _rv = (QuantLib::DiscountFactor)(*_ppLiborForwardModel)->discount ( _t );   
        Double _nrv = (Double)ValueHelper::Convert (_rv); //c
    	return _nrv;
	}
    catch (QuantLib::Error& _error)
    {
        if (_error.what())
		    throw REFNEW NativeExcpetion (REFNEW PLATFORM::String(_error.what()));
        else
		    throw REFNEW NativeExcpetion (REFNEW PLATFORM::String("Unknown quantlib error"));
        
    }
	catch (std::exception& _error)
	{
        if (_error.what())
		    throw REFNEW NativeExcpetion (REFNEW PLATFORM::String(_error.what()));
        else
		    throw REFNEW NativeExcpetion (REFNEW PLATFORM::String("Unknown std::exception"));
	}
    finally
    {
    }
}
Double Cephei::QL::Legacy::Libormarketmodels::CLiborForwardModel::DiscountBond (Double now, Double maturity, Cephei::QL::Math::IArray^ factors)
{
    CArray^ _Cfactors;
    try
    {
        QuantLib::Time _now = (QuantLib::Time)ValueHelper::Convert (now); //a
        QuantLib::Time _maturity = (QuantLib::Time)ValueHelper::Convert (maturity); //a
        _Cfactors = safe_cast<CArray^> (factors);
        _Cfactors->Lock();
        QuantLib::Array _factors = static_cast<QuantLib::Array> (_Cfactors->GetReference ()); 
    	QuantLib::Real _rv = (QuantLib::Real)(*_ppLiborForwardModel)->discountBond ( _now,  _maturity,  _factors );   
        Double _nrv = (Double)ValueHelper::Convert (_rv); //c
    	return _nrv;
	}
    catch (QuantLib::Error& _error)
    {
        if (_error.what())
		    throw REFNEW NativeExcpetion (REFNEW PLATFORM::String(_error.what()));
        else
		    throw REFNEW NativeExcpetion (REFNEW PLATFORM::String("Unknown quantlib error"));
        
    }
	catch (std::exception& _error)
	{
        if (_error.what())
		    throw REFNEW NativeExcpetion (REFNEW PLATFORM::String(_error.what()));
        else
		    throw REFNEW NativeExcpetion (REFNEW PLATFORM::String("Unknown std::exception"));
	}
    finally
    {
        if (_Cfactors != nullptr) _Cfactors->Unlock();
    }
}
Double Cephei::QL::Legacy::Libormarketmodels::CLiborForwardModel::DiscountBondOption (QL::Option::TypeEnum type, Double strike, Double maturity, Double bondMaturity)
{
    try
    {
        QuantLib::Option::Type _type = (QuantLib::Option::Type)type ;
        QuantLib::Real _strike = (QuantLib::Real)ValueHelper::Convert (strike); //a
        QuantLib::Time _maturity = (QuantLib::Time)ValueHelper::Convert (maturity); //a
        QuantLib::Time _bondMaturity = (QuantLib::Time)ValueHelper::Convert (bondMaturity); //a
    	QuantLib::Real _rv = (QuantLib::Real)(*_ppLiborForwardModel)->discountBondOption ( _type,  _strike,  _maturity,  _bondMaturity );   
        Double _nrv = (Double)ValueHelper::Convert (_rv); //c
    	return _nrv;
	}
    catch (QuantLib::Error& _error)
    {
        if (_error.what())
		    throw REFNEW NativeExcpetion (REFNEW PLATFORM::String(_error.what()));
        else
		    throw REFNEW NativeExcpetion (REFNEW PLATFORM::String("Unknown quantlib error"));
        
    }
	catch (std::exception& _error)
	{
        if (_error.what())
		    throw REFNEW NativeExcpetion (REFNEW PLATFORM::String(_error.what()));
        else
		    throw REFNEW NativeExcpetion (REFNEW PLATFORM::String("Unknown std::exception"));
	}
    finally
    {
    }
}
Cephei::QL::Termstructures::Volatility::Swaption::ISwaptionVolatilityMatrix^ Cephei::QL::Legacy::Libormarketmodels::CLiborForwardModel::GetSwaptionVolatilityMatrix::get ()
{
    try
    {
    	boost::shared_ptr<QuantLib::SwaptionVolatilityMatrix> _rv = (boost::shared_ptr<QuantLib::SwaptionVolatilityMatrix>)(*_ppLiborForwardModel)->getSwaptionVolatilityMatrix ( );   
        Cephei::QL::Termstructures::Volatility::Swaption::CSwaptionVolatilityMatrix^ _nrv = REFNEW Cephei::QL::Termstructures::Volatility::Swaption::CSwaptionVolatilityMatrix (_rv, this);
    	return _nrv;
	}
    catch (QuantLib::Error& _error)
    {
        if (_error.what())
		    throw REFNEW NativeExcpetion (REFNEW PLATFORM::String(_error.what()));
        else
		    throw REFNEW NativeExcpetion (REFNEW PLATFORM::String("Unknown quantlib error"));
        
    }
	catch (std::exception& _error)
	{
        if (_error.what())
		    throw REFNEW NativeExcpetion (REFNEW PLATFORM::String(_error.what()));
        else
		    throw REFNEW NativeExcpetion (REFNEW PLATFORM::String("Unknown std::exception"));
	}
    finally
    {
    }
}
Double Cephei::QL::Legacy::Libormarketmodels::CLiborForwardModel::S_0 (UInt64 alpha, UInt64 beta)
{
    try
    {
        QuantLib::Size _alpha = (QuantLib::Size)ValueHelper::Convert (alpha); //a
        QuantLib::Size _beta = (QuantLib::Size)ValueHelper::Convert (beta); //a
    	QuantLib::Rate _rv = (QuantLib::Rate)(*_ppLiborForwardModel)->S_0 ( _alpha,  _beta );   
        Double _nrv = (Double)ValueHelper::Convert (_rv); //c
    	return _nrv;
	}
    catch (QuantLib::Error& _error)
    {
        if (_error.what())
		    throw REFNEW NativeExcpetion (REFNEW PLATFORM::String(_error.what()));
        else
		    throw REFNEW NativeExcpetion (REFNEW PLATFORM::String("Unknown quantlib error"));
        
    }
	catch (std::exception& _error)
	{
        if (_error.what())
		    throw REFNEW NativeExcpetion (REFNEW PLATFORM::String(_error.what()));
        else
		    throw REFNEW NativeExcpetion (REFNEW PLATFORM::String("Unknown std::exception"));
	}
    finally
    {
    }
}
Cephei::QL::Legacy::Libormarketmodels::ILiborForwardModel^ Cephei::QL::Legacy::Libormarketmodels::CLiborForwardModel::SetParams (Cephei::QL::Math::IArray^ p_params)
{
    CArray^ _Cp_params;
    try
    {
    	boost::detail::spinlock::scoped_lock lock (*_pSpinlock);
        _Cp_params = safe_cast<CArray^> (p_params);
        _Cp_params->Lock();
        QuantLib::Array& _p_params = static_cast<QuantLib::Array&> (_Cp_params->GetReference ()); 
    	(*_ppLiborForwardModel)->setParams ( _p_params );
    	return this;
	}
    catch (QuantLib::Error& _error)
    {
        if (_error.what())
		    throw REFNEW NativeExcpetion (REFNEW PLATFORM::String(_error.what()));
        else
		    throw REFNEW NativeExcpetion (REFNEW PLATFORM::String("Unknown quantlib error"));
        
    }
	catch (std::exception& _error)
	{
        if (_error.what())
		    throw REFNEW NativeExcpetion (REFNEW PLATFORM::String(_error.what()));
        else
		    throw REFNEW NativeExcpetion (REFNEW PLATFORM::String("Unknown std::exception"));
	}
    finally
    {
        if (_Cp_params != nullptr) _Cp_params->Unlock();
    }
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Factory class

Cephei::QL::Legacy::Libormarketmodels::ILiborForwardModel^ Cephei::QL::Legacy::Libormarketmodels::CLiborForwardModel_Factory::Create (Cephei::QL::Legacy::Libormarketmodels::ILiborForwardModelProcess^ process, Cephei::QL::Legacy::Libormarketmodels::ILmVolatilityModel^ volaModel, Cephei::QL::Legacy::Libormarketmodels::ILmCorrelationModel^ corrModel)
{
    return REFNEW CLiborForwardModel ( process,  volaModel,  corrModel);
}
